---
export interface Props {
  currentPage: number;
  lastPage: number;
  urlPrev: string | null;
  urlNext: string | null;
  basePath: string;
  maxDisplayedPages: number;
}

const {
  currentPage,
  lastPage,
  urlPrev,
  urlNext,
  basePath,
  maxDisplayedPages = 5,
} = Astro.props;

const startPage = Math.max(
  1,
  Math.min(
    currentPage - Math.floor(maxDisplayedPages / 2),
    lastPage - maxDisplayedPages + 1,
  ),
);
const endPage = Math.min(lastPage, startPage + maxDisplayedPages - 1);

function ensureTrailingSlash(path: string) {
  return path.endsWith("/") ? path : `${path}/`;
}

const computedBasePath = basePath ? ensureTrailingSlash(basePath) : "/page/";
---

<nav
  class="mt-8 flex items-center justify-center gap-x-1"
  aria-label="Pagination"
>
  {
    urlPrev ? (
      <a
        href={ensureTrailingSlash(urlPrev)}
        aria-label="Previous page"
        class="inline-flex min-h-[38px] min-w-[38px] items-center justify-center gap-x-1.5 rounded-lg px-2.5 py-2 text-sm"
      >
        <i class="i-tabler-chevron-left icon-base"></i>
      </a>
    ) : (
      ""
    )
  }
  <ul class="flex items-center gap-x-1">
    {
      Array.from({ length: endPage - startPage + 1 }, (_, i) => {
        const pageNumber = startPage + i;
        const isActive = currentPage === pageNumber;
        const pageClass = `min-h-[38px] min-w-[38px] flex justify-center items-center py-2 px-3 text-sm rounded-lg ${isActive ? "bg-base-300" : ""}`;
        return (
          <li>
            <a
              href={`${computedBasePath}${pageNumber}/`}
              class={pageClass}
              aria-current={isActive ? "page" : undefined}
            >
              {pageNumber}
            </a>
          </li>
        );
      })
    }
  </ul>
  {
    urlNext ? (
      <a
        href={ensureTrailingSlash(urlNext)}
        aria-label="Next page"
        class="inline-flex min-h-[38px] min-w-[38px] items-center justify-center gap-x-1.5 rounded-lg px-2.5 py-2 text-sm"
      >
        <i class="icon-[tabler--chevron-right] icon-base"></i>
      </a>
    ) : (
      ""
    )
  }
</nav>
